package conversation

import (
	"context"

	"gitee.com/gao-deguang/easy-chat/apps/im/ws/internal/svc"
	"gitee.com/gao-deguang/easy-chat/apps/im/ws/websocket"
	"gitee.com/gao-deguang/easy-chat/apps/im/ws/ws"
	"gitee.com/gao-deguang/easy-chat/apps/task/mq/mq"
	"gitee.com/gao-deguang/easy-chat/pkg/constant"
	"github.com/mitchellh/mapstructure"
	"github.com/zeromicro/go-zero/core/logx"
)

func Chat(svc *svc.ServiceContext) websocket.HandleFunc {
	return func(svr *websocket.Server, conn *websocket.Conn, msg *websocket.Message) {
		var data ws.Chat
		if err := mapstructure.Decode(msg.Data, &data); err != nil {
			svr.Send(websocket.NewErrMessage(err), conn)
			return
		}
		logx.Info("ChatDataChatDataChatData:", data)

		switch data.ChatType {
		case constant.SingleChat:
		case constant.GroupChat:
			data.ConversationId = data.RecvId
		}

		recvServerAddr := svr.Discover.GetRecverServerAddr(data.RecvId)
		if recvServerAddr != svr.GetAddr() {
			//recver不在本服务器,将原始请求转发到目标服务器
			logx.Info("recver不在本服务器,调整往MQ推送的消息\n")
			logx.Info("本服务器地址", svr.GetAddr(), "\n")
			logx.Info("目标服务器地址", recvServerAddr, "\n")
			//cli := svr.Discover.GetAClient(recvServerAddr)

		}
		logx.Info("Ws往消息队列里推送消息了:", data)
		err := svc.MsgChatTransferClient.Push(context.Background(), &mq.MsgChatTransfer{
			ConversationId: data.ConversationId,
			ChatType:       data.ChatType,
			SendId:         data.SendId,
			SendServerAddr: recvServerAddr,
			RecvId:         data.RecvId,
			SendTime:       data.SendTime,
			Mtype:          data.Mtype,
			Content:        data.Content,
		})
		if err != nil {
			svr.Send(websocket.NewErrMessage(err), conn)
			// 	return
		}
		// err := logic.NewConversation(context.Background(), svr, svc).SingleChat(&data, conn.Uid)
		// if err != nil {
		// 	svr.Send(websocket.NewErrMessage(err), conn)
		// 	return
		// }

		// svr.SendByUserId(websocket.NewMessage(data.SendId, ws.Chat{
		// 	ConversationId: data.ConversationId,
		// 	ChatType:       data.ChatType,
		// 	SendId:         conn.Uid,
		// 	RecvId:         data.RecvId,
		// 	SendTime:       time.Now().UnixMilli(),
		// 	Msg:            data.Msg,
		// }), data.RecvId)

		//推送到消息队列中

	}
}

func MarkRead(svc *svc.ServiceContext) websocket.HandleFunc {
	return func(svr *websocket.Server, conn *websocket.Conn, msg *websocket.Message) {
		var data ws.MarkRead
		if err := mapstructure.Decode(msg.Data, &data); err != nil {
			svr.Send(websocket.NewErrMessage(err), conn)
			return
		}
		logx.Info("MarkreadDataMarkreadDataMarkreadDataMarkreadData:", data)

		err := svc.MsgReadTransferClient.Push(context.Background(), &mq.MsgMarkRead{
			ChatType:       data.ChatType,
			ConversationId: data.ConversationId,
			SendId:         conn.Uid,
			RecvId:         data.RecvId,
			MsgIds:         data.MsgIds,
		})
		if err != nil {
			svr.Send(websocket.NewErrMessage(err), conn)
			// 	return
		}

	}
}
